package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.service.ResumeService;
import com.blog.blog.service.ResumePdfService;
import com.blog.blog.vo.ResumeDetailVO;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestHeader;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;

@Tag(name = "简历管理", description = "个人简历信息、工作经验、技能、项目、教育背景管理接口")
@RestController
@RequestMapping("/api/resume")
public class ResumeController {

	private final ResumeService resumeService;
	private final ResumePdfService resumePdfService;
	private final com.blog.blog.service.AuthService authService;

	public ResumeController(ResumeService resumeService, ResumePdfService resumePdfService, com.blog.blog.service.AuthService authService) {
		this.resumeService = resumeService;
		this.resumePdfService = resumePdfService;
		this.authService = authService;
	}

	@GetMapping
	public ApiBaseResponse<ResumeDetailVO> getResume() {
		return ApiBaseResponse.success(resumeService.getResume());
	}

	@GetMapping("/me")
	public ApiBaseResponse<ResumeDetailVO> getMyResume(@RequestHeader(value = "Authorization", required = false) String authorization) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.getResumeByUserId(userId));
	}

	@GetMapping("/{userId}")
	public ApiBaseResponse<ResumeDetailVO> getResumeByUser(@PathVariable("userId") Long userId) {
		return ApiBaseResponse.success(resumeService.getResumeByUserId(userId));
	}

	@PutMapping
	public ApiBaseResponse<Boolean> upsertMyResume(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                   @RequestBody com.blog.blog.dto.SaveResumeDTO dto) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.upsertResume(userId, dto));
	}

	// 经验 CRUD
	@PostMapping("/experiences")
	public ApiBaseResponse<Long> addExperience(@RequestHeader(value = "Authorization", required = false) String authorization,
                                               @RequestBody com.blog.blog.vo.WorkExperienceVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.addExperience(userId, vo));
	}

	@PutMapping("/experiences/{id}")
	public ApiBaseResponse<Boolean> updateExperience(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                     @PathVariable("id") Long id,
                                                     @RequestBody com.blog.blog.vo.WorkExperienceVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		vo.setId(id);
		return ApiBaseResponse.success(resumeService.updateExperience(userId, vo));
	}

	@DeleteMapping("/experiences/{id}")
	public ApiBaseResponse<Boolean> deleteExperience(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                     @PathVariable("id") Long id) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.deleteExperience(userId, id));
	}

	// 技能 CRUD
	@PostMapping("/skills")
	public ApiBaseResponse<Long> addSkill(@RequestHeader(value = "Authorization", required = false) String authorization,
                                          @RequestBody com.blog.blog.vo.SkillVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.addSkill(userId, vo));
	}

	@PutMapping("/skills/{id}")
	public ApiBaseResponse<Boolean> updateSkill(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                @PathVariable("id") Long id,
                                                @RequestBody com.blog.blog.vo.SkillVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		vo.setId(id);
		return ApiBaseResponse.success(resumeService.updateSkill(userId, vo));
	}

	@DeleteMapping("/skills/{id}")
	public ApiBaseResponse<Boolean> deleteSkill(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                @PathVariable("id") Long id) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.deleteSkill(userId, id));
	}

	// 项目 CRUD
	@PostMapping("/projects")
	public ApiBaseResponse<Long> addProject(@RequestHeader(value = "Authorization", required = false) String authorization,
                                            @RequestBody com.blog.blog.vo.ProjectVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.addProject(userId, vo));
	}

	@PutMapping("/projects/{id}")
	public ApiBaseResponse<Boolean> updateProject(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                  @PathVariable("id") Long id,
                                                  @RequestBody com.blog.blog.vo.ProjectVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		vo.setId(id);
		return ApiBaseResponse.success(resumeService.updateProject(userId, vo));
	}

	@DeleteMapping("/projects/{id}")
	public ApiBaseResponse<Boolean> deleteProject(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                  @PathVariable("id") Long id) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.deleteProject(userId, id));
	}

	// 教育背景 CRUD
	@PostMapping("/educations")
	public ApiBaseResponse<Long> addEducation(@RequestHeader(value = "Authorization", required = false) String authorization,
                                              @RequestBody com.blog.blog.vo.EducationVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.addEducation(userId, vo));
	}

	@PutMapping("/educations/{id}")
	public ApiBaseResponse<Boolean> updateEducation(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                    @PathVariable("id") Long id,
                                                    @RequestBody com.blog.blog.vo.EducationVO vo) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		vo.setId(id);
		return ApiBaseResponse.success(resumeService.updateEducation(userId, vo));
	}

	@DeleteMapping("/educations/{id}")
	public ApiBaseResponse<Boolean> deleteEducation(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                    @PathVariable("id") Long id) {
		Long userId = extractUserId(authorization);
		if (userId == null) return ApiBaseResponse.error(401, "未授权");
		return ApiBaseResponse.success(resumeService.deleteEducation(userId, id));
	}

	@Operation(summary = "导出简历PDF", description = "将个人简历导出为PDF文件")
	@GetMapping("/pdf")
	@SecurityRequirement(name = "Bearer Authentication")
	public ResponseEntity<byte[]> exportResumePdf(@RequestHeader(value = "Authorization", required = false) String authorization) {
		Long userId = extractUserId(authorization);
		if (userId == null) {
			return ResponseEntity.status(401).build();
		}
		
		try {
			byte[] pdfBytes = resumePdfService.generateResumePdf(userId);
			if (pdfBytes == null) {
				return ResponseEntity.notFound().build();
			}
			
			String fileName = resumePdfService.getResumePdfFileName(userId);
			
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_PDF);
			headers.setContentDispositionFormData("attachment", fileName);
			headers.setContentLength(pdfBytes.length);
			
			return ResponseEntity.ok()
				.headers(headers)
				.body(pdfBytes);
				
		} catch (Exception e) {
			return ResponseEntity.internalServerError().build();
		}
	}
	
	@Operation(summary = "预览简历PDF", description = "在浏览器中预览简历PDF")
	@GetMapping("/pdf/preview")
	@SecurityRequirement(name = "Bearer Authentication")
	public ResponseEntity<byte[]> previewResumePdf(@RequestHeader(value = "Authorization", required = false) String authorization) {
		Long userId = extractUserId(authorization);
		if (userId == null) {
			return ResponseEntity.status(401).build();
		}
		
		try {
			byte[] pdfBytes = resumePdfService.generateResumePdf(userId);
			if (pdfBytes == null) {
				return ResponseEntity.notFound().build();
			}
			
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_PDF);
			headers.setContentDispositionFormData("inline", "resume_preview.pdf");
			headers.setContentLength(pdfBytes.length);
			
			return ResponseEntity.ok()
				.headers(headers)
				.body(pdfBytes);
				
		} catch (Exception e) {
			return ResponseEntity.internalServerError().build();
		}
	}

	private Long extractUserId(String authorization) {
		if (authorization == null || !authorization.startsWith("Bearer ")) return null;
		String token = authorization.substring(7);
		return authService.verify(token);
	}
}


